import { useEffect } from 'react'
import { toast } from 'react-toastify'

/**
 * 键盘快捷键Hook
 * @param {Object} shortcuts - 快捷键配置对象
 * @param {boolean} enabled - 是否启用快捷键
 */
export function useKeyboardShortcuts(shortcuts, enabled = true) {
  useEffect(() => {
    if (!enabled) return

    const handleKeyDown = (e) => {
      // 如果在输入框中，不触发快捷键
      if (
        e.target.tagName === 'INPUT' ||
        e.target.tagName === 'TEXTAREA' ||
        e.target.isContentEditable
      ) {
        // 除了 Escape 键
        if (e.key !== 'Escape') return
      }

      const key = e.key.toLowerCase()
      const ctrl = e.ctrlKey || e.metaKey
      const shift = e.shiftKey
      const alt = e.altKey

      // 构建快捷键字符串
      let shortcut = ''
      if (ctrl) shortcut += 'ctrl+'
      if (shift) shortcut += 'shift+'
      if (alt) shortcut += 'alt+'
      shortcut += key

      // 查找匹配的快捷键
      const matchedShortcut = Object.entries(shortcuts).find(
        ([sc]) => sc.toLowerCase() === shortcut
      )

      if (matchedShortcut) {
        const [, handler] = matchedShortcut
        e.preventDefault()
        handler(e)
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [shortcuts, enabled])
}

/**
 * 显示快捷键帮助
 */
export function showShortcutsHelp() {
  const shortcuts = [
    { key: 'Esc', description: '关闭弹窗/对话框' },
    { key: 'Ctrl + S', description: '保存/下单' },
    { key: 'Ctrl + Z', description: '撤销操作' },
    { key: 'Space', description: '开始/暂停旋转' },
    { key: 'R', description: '重置3D视角' },
    { key: 'F', description: '全屏模式' },
    { key: 'Ctrl + O', description: '打开订单列表' },
    { key: 'Ctrl + L', description: '打开登录' },
    { key: '?', description: '显示快捷键帮助' }
  ]

  const helpText = shortcuts
    .map(s => `⌨️ ${s.key} - ${s.description}`)
    .join('\n\n')

  toast.info(helpText, {
    autoClose: 8000,
    closeButton: true,
    className: 'glass-effect-dark border border-white/10',
    style: {
      whiteSpace: 'pre-line',
      fontFamily: 'monospace'
    }
  })
}

